package com.cangshi.controller;

import com.alibaba.fastjson.JSON;
import com.cangshi.dao.GroupMapper;
import com.cangshi.entity.*;
import com.cangshi.service.*;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * Created by Eoly on 2016/12/22.
 */

@Controller
public class GroupUserController {

    @Autowired
    GroupService groupService;

    @Autowired
    UserService userService;

    @Autowired
    BillService billService;

    @Autowired
    OrderService orderService;

    @Autowired
    AddressService addressService;

    @Autowired
    GroupUserService groupUserService;

    private static final Logger LOGGER = Logger.getLogger(GroupUserController.class);

    @ResponseBody
    @RequestMapping(value = "/user/group/join-group", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    public JsonObject findGroupType(@RequestParam(required = false) Integer groupId, @RequestParam(required = false) Integer addressId, HttpServletRequest request) {
        JsonObject<Order> jsonObject = new JsonObject<Order>();

        //获得用户
        UserBaseInfo userLogin = (UserBaseInfo) request.getAttribute("user");

        //检查数据完整性
        if (groupId == null || addressId == null) {

            jsonObject.setError(731);
            jsonObject.setMes("参数不完整:请求需要团id以及地址信息id");
            return jsonObject;
        }
        //获取用户信息
        User checkUser = userService.getUserById(userLogin.getUserId());

        //获取地址信息
        Address address = addressService.findAddressByAddressId(addressId);
        if (address == null) {

            jsonObject.setError(732);
            jsonObject.setMes("暂时没有找到地址id为:" + addressId + "，请稍候再试");
            return jsonObject;
        }
        if (!address.getUserId().equals(userLogin.getUserId())) {
            jsonObject.setError(732);
            jsonObject.setMes("该地址非该用户的地址");
            return jsonObject;
        }

        //获取欲参加的团
        Group preGroup = groupService.findGroupByGroupId(groupId);
        if (preGroup == null) {

            jsonObject.setError(732);
            jsonObject.setMes("暂时没有找到团id为:" + groupId + "，请稍候再试");
            return jsonObject;
        }

        //获取团状态
        if (preGroup.getGroupStatus() != 0) {

            jsonObject.setError(734);
            jsonObject.setMes("该团目前不可以加入");
            return jsonObject;
        }

        //判断用户是否为该团的发起者
        if (userLogin.getUserId().equals(preGroup.getGroupInitiatorId())) {

            jsonObject.setError(738);
            jsonObject.setMes("该团的发起者不可参加该团");
            return jsonObject;
        }

        //判断用户是否已参团
        GroupUserKey checkGroupUser = new GroupUserKey();
        checkGroupUser.setGroupId(preGroup.getGroupId());
        List<GroupUserKey> groupUserKeyList = groupUserService.findIdByRequestId(checkGroupUser);
        if (!groupUserKeyList.isEmpty()) {
            for (GroupUserKey groupUserKey : groupUserKeyList) {
                //判断用户是否参团
                if (userLogin.getUserId().equals(groupUserKey.getUserId())) {
                    jsonObject.setError(736);
                    jsonObject.setMes("该用户已经参加此团");
                    return jsonObject;
                }
            }
        }

        //判断团参加人数是否超标
        if (preGroup.getGroupTargetNumber() <= groupUserKeyList.size()) {

            jsonObject.setError(735);
            jsonObject.setMes("参团人数已达上限");
            return jsonObject;
        }

        //获取团预支总额
        Double money = preGroup.getGroupPostage() + preGroup.getGroupPrice();

        //生成订单
        Order order = new Order();
        order.setGroupId(preGroup.getGroupId());
        order.setUserId(userLogin.getUserId());
        order.setOrderMoney(money);
        order.setOrderUserId(preGroup.getGroupInitiatorId());
        order.setOrderStatus(0);
        order.setOrderAddressId(addressId);
        //获取订单生成结果
        Integer resultForOrder = orderService.addOrder(order);

        if (resultForOrder != 1) {
            jsonObject.setError(738);
            jsonObject.setMes("生成订单失败");
            return jsonObject;
        }

        //获得订单id
        order.setOrderId(orderService.findLastId());

        jsonObject.setError(0);
        jsonObject.setData(order);
        jsonObject.setMes("成功生成订单，等待支付");


        //返回结果
        return jsonObject;
    }


    /**
     * 获取用户已参加的团 功能
     *
     * @param groupStatus
     * @param line
     * @param next
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/user/group/show-joined-groups", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    public JsonObject findGroupsJoined(@RequestParam(required = false) Integer groupStatus, @RequestParam(required = false) Integer line, @RequestParam(required = false) Integer next, HttpServletRequest request) {
        JsonObject<Group> jsonObject = new JsonObject<Group>();

        //获得用户
        UserBaseInfo userLogin = (UserBaseInfo) request.getAttribute("user");

        Group checkGroup = null;
        //检查数据合法性
        if (groupStatus != null && groupStatus >= -1 && groupStatus <= 2) {
            checkGroup = new Group();
            checkGroup.setGroupStatus(groupStatus);
        }

        //获取查询数据
        List<Group> groupList = groupUserService.findGroupsByUserIdCheckAndLimit(userLogin.getUserId(), checkGroup, line, next);

        if (groupList.isEmpty()) {
            jsonObject.setError(781);
            jsonObject.setMes("该用户没有参加符合条件的团");
            return jsonObject;
        }

        //封装查询结果
        jsonObject.setError(0);
        jsonObject.setDataList(groupList);
        jsonObject.setMes("获取成功共" + groupList.size() + "条团信息");


        //返回结果
        return jsonObject;
    }

    /**
     * 获取用户有关的所有团 功能
     *
     * @param groupStatus
     * @param line
     * @param next
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/user/group/show-all-groups", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    public JsonObject findAllGroupsAbout(@RequestParam(required = false) Integer groupStatus, @RequestParam(required = false) Integer line, @RequestParam(required = false) Integer next, HttpServletRequest request) {
        JsonObject<Group> jsonObject = new JsonObject<Group>();

        //获得用户
        UserBaseInfo userLogin = (UserBaseInfo) request.getAttribute("user");

        Group checkGroup = null;
        //检查数据合法性
        if (groupStatus != null && groupStatus >= -1 && groupStatus <= 2) {
            checkGroup = new Group();
            checkGroup.setGroupStatus(groupStatus);
        }

        //获取查询数据
        List<Group> groupList = groupUserService.findAllGroupsByUserIdCheckAndLimit(userLogin.getUserId(), checkGroup, line, next);

        if (groupList.isEmpty()) {
            jsonObject.setError(781);
            jsonObject.setMes("该用户于任何团没有关系");
            return jsonObject;
        }

        //封装查询结果
        jsonObject.setError(0);
        jsonObject.setDataList(groupList);
        jsonObject.setMes("获取成功共" + groupList.size() + "条团信息");


        //返回结果
        return jsonObject;
    }

}